package com.xiaomiMall.mange.controller;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.xiaomiMall.mange.domain.MallLoginBody;
import com.xiaomiMall.mange.domain.MallLoginUser;
import com.xiaomiMall.mange.domain.MallUser;
import com.xiaomiMall.mange.service.Impl.MallTokenServiceImpl;
import com.xiaomiMall.mange.service.MallLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/api")
public class MallLoginController extends BaseController {

    @Autowired
    private MallLoginService mallLoginService;

    @Autowired
    private MallTokenServiceImpl mallTokenService;

    /**
     * 商城登陆方法
     * @param mallLoginBody 登陆信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody MallLoginBody mallLoginBody) {
        AjaxResult ajax = null;
        // 验证用户名密码
        String token = mallLoginService.checkPassword(mallLoginBody);
        if (StringUtils.isNotNull(token)) {
            ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            ajax.replace("msg", "密码正确");
        } else {
            ajax = error("账号或密码错误");
        }
        return ajax;
    }

    /**
     * 获取用户信息
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo(HttpServletRequest request)
    {
        AjaxResult ajax = null;
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            MallUser user = mallLoginUser.getMallUser();
            user.setPassword("");
            ajax = AjaxResult.success();
            ajax.put("user", user);
        } else {
            ajax = AjaxResult.error(401,"登陆状态已过期");
        }
        return ajax;
    }

    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        //后台好像没有接到请求
        MallLoginUser mallLoginUser = mallTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(mallLoginUser)) {
            mallTokenService.delLoginUser(mallLoginUser.getToken());
        }
        return null;
    }

}
